import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

public class Leetcode1302 {
    private int maxLevel = 0;
    private int sum = 0;


    public int deepestLeavesSum(TreeNode root) {
        dfs(root, 0);

        return sum;
    }

    private void dfs(TreeNode root, int level) {
        if (root == null) {
            return;
        }

        if (level == maxLevel) {
            sum += root.val;
        }

        if (level > maxLevel) {
            sum = root.val;
            maxLevel = level;
        }

        dfs(root.left, level + 1);
        dfs(root.right, level + 1);
    }

    /**
     * 迭代版本层次遍历
     *
     * @param root
     * @return
     */
    public int deepestLeavesSum1(TreeNode root) {
        if (root == null) {
            return 0;
        }

        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        int res = 0;
        while (!queue.isEmpty()) {
            res = 0;
            int size = queue.size();

            for (int i = 0; i < size; i++) {
                TreeNode node = queue.poll();
                res += node.val;

                if (node.left != null) {
                    queue.add(node.left);
                }
                if (node.right != null) {
                    queue.add(node.right);
                }
            }
        }

        return res;
    }
}

